package cn.xing.modules.app.service.impl;

import cn.hutool.captcha.generator.RandomGenerator;
import cn.xing.common.utils.RedisUtils;
import cn.xing.modules.app.service.SmsService;
import cn.xing.modules.app.service.VerificationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class VerificationServiceImpl implements VerificationService {
    @Autowired
    private SmsService smsService;

    @Value("${alibaba.sms.debug: false}")
    private boolean smsDebug;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void sendLoginSmsCode(String prefix, String phone) {

        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        String code = randomGenerator.generate();

        redisUtils.set(prefix + phone, code);

        smsService.sendSms(phone, code);
    }

    @Override
    public boolean checkSmsCode(String prefix, String phone, String code) {
        // debug 验证码为1放行
        if (smsDebug) {
            if ("1".equals(code)){
                return true;
            }
        }

        String redisCode = redisUtils.get(prefix + phone);
        if (StringUtils.isEmpty(phone)) {
            return false;
        }
        // 验证码匹配
        if (code.equals(redisCode)) {
            // 成功删除验证码
            redisUtils.delete(prefix+phone);

            return true;
        }
        return false;
    }
}
